<template>
  <div>
    <el-card shadow="never">
      <el-button class="mb-8" type="primary" plain @click="addDialogVisible = true">新增任务</el-button>
      <el-table :data="tableData" v-loading="tableLoading" style="width: 100%">
        <el-table-column fixed prop="description" label="任务描述" width="150" align="center"/>
        <el-table-column prop="name" label="调用目标" width="400" align="center">
          <template #default="scope">
            <span type="primary">*.{{ getClassSimpleName(scope.row.name) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="group" label="分组" width="120" align="center">
          <template #default="scope">
            <el-tag type="primary">{{ scope.row.group }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cronExpression" label="cron执行表达式" width="220"/>
        <el-table-column prop="state" label="状态" width="120" align="center">
          <template #default="scope">
            <span v-if="scope.row.state === 'NORMAL'">
                <el-tag type="success">正常</el-tag>
            </span>
            <span v-if="scope.row.state === 'COMPLETE'">
                <el-tag type="success">完成</el-tag>
            </span>
            <span v-if="scope.row.state === 'ERROR'">
                <el-tag type="danger">错误</el-tag>
            </span>
            <span v-if="scope.row.state === 'NONE'">
                <el-tag type="warning">不存在</el-tag>
            </span>
            <span v-if="scope.row.state === 'BLOCKED'">
                <el-tag type="warning">阻塞</el-tag>
            </span>
            <span v-if="scope.row.state === 'PAUSED'">
                <el-tag type="primary">暂停</el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="250" align="left">
          <template #default="scope">
            <el-button link type="primary" size="large" @click="doRun(scope.row)">执行</el-button>
            <el-button link type="primary" size="large" @click="doReschedule(scope.row)">修改</el-button>
            <el-button link type="success" size="large" @click="doResume(scope.row)">重启</el-button>
            <el-button link type="warning" size="large" @click="doPause(scope.row)">暂停</el-button>
            <el-button link type="danger" size="large" @click="doDel(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增定时任务对话框 -->
    <el-dialog
        v-model="addDialogVisible"
        title="新增定时任务"
        width="500"
        :before-close="handleClose"
    >
      <el-form
          label-position="left"
          label-width="100px"
          :model="addJobForm"
          style="max-width: 460px"
          ref="addFormRef"
          :rules="rules"
      >
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="addJobForm.description"/>
        </el-form-item>
        <el-form-item label="调用目标" prop="name">
          <el-input v-model="addJobForm.name"/>
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="addJobForm.group"/>
        </el-form-item>
        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-model="addJobForm.cronExpression"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="addFormLoading">
            发布
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 修改定时任务对话框-->
    <el-dialog
        v-model="updateDialogVisible"
        title="新增定时任务"
        width="500"
        :before-close="handleClose"
    >
      <el-form
          label-position="left"
          label-width="100px"
          :model="updateJobForm"
          style="max-width: 460px"
          ref="updateFormRef"
          :rules="rules"
      >
        <el-form-item label="任务描述" prop="description">
          <el-input v-model="updateJobForm.description"/>
        </el-form-item>
        <el-form-item label="调用目标" prop="name">
          <el-input v-model="updateJobForm.name"/>
        </el-form-item>
        <el-form-item label="分组" prop="group">
          <el-input v-model="updateJobForm.group"/>
        </el-form-item>
        <el-form-item label="cron表达式" prop="cronExpression">
          <el-input v-model="updateJobForm.cronExpression"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="onUpdate" :loading="updateFormLoading">
            更新
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref, reactive} from "vue";
import {query, add, run, resume, del, pause, reschedule} from "@/api/admin/job.js"
import {showModel, showNotification} from "@/composables/util.js";

// 新增表格弹窗显示控制
const addDialogVisible = ref(false)
// 表格数据
const tableData = ref([])
// 新增表单引用
const addFormRef = ref(null)
// 新增定时任务提交 loading
const addFormLoading = ref(false)
// 表单加载
const tableLoading = ref(false)
// 修改定时任务对话框
const updateDialogVisible = ref(false)
// 新增表单引用
const updateFormRef = ref(null)
// 新增定时任务提交 loading
const updateFormLoading = ref(false)
// 新增表单待填
const addJobForm = reactive({
  name: '',
  description: '',
  group: 'default',
  cronExpression: '',
})
const updateJobForm = reactive({
  name: '',
  description: '',
  group: 'default',
  cronExpression: '',
})
// 规则校验
const rules = {
  name: [{required: true, message: '调用目标不能为空', trigger: 'blur'}],
  description: [{required: true, message: '任务描述不能为空', trigger: 'blur'}],
  group: [{required: true, message: '请输入分组', trigger: 'blur'}],
  cronExpression: [{required: true, message: 'cron表达式不能为空', trigger: 'blur'}]
}

onMounted(() => {
  getJobList()
})

function getJobList() {
  tableLoading.value = true
  query().then(resp => {
    if (resp.success) {
      tableData.value = resp.data
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

const handleClose = () => {
  addDialogVisible.value = false
  updateDialogVisible.value = false
}

// 提交新增定时任务表单
const onSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) {
      console.log("表单校验不通过")
      return false
    }
  })
  addFormLoading.value = true
  add(addJobForm).then(resp => {
    if (resp.success) {
      showNotification("定时任务", "新增定时任务成功！")
    } else {
      showNotification("定时任务", resp.message, "warning")
    }
  }).finally(() => {
    addFormLoading.value = false
    addDialogVisible.value = false
    addJobForm.name = ''
    addJobForm.description = ''
    addJobForm.group = 'default'
    addJobForm.cronExpression = ''
    getJobList()
  })
}

// 得到简短的类名
const getClassSimpleName = (fullClassName) => {
  // 使用字符串切割方法获取类名的最后一部分
  const parts = fullClassName.split('.');
  return parts[parts.length - 1];
}

// 定时任务一些操作
const doRun = (row) => {
  const data = {
    "name": row.name,
    "group": row.group
  }
  tableLoading.value = true
  run(data).then(resp => {
    if (resp.success) {
      showNotification("定时任务", "手动执行定时任务成功")
    } else {
      showNotification("定时任务", resp.message, "warning")
    }
  }).finally(() => {
    getJobList()
    tableLoading.value = false
  })
}
// 重新执行
const doResume = (row) => {
  const data = {
    "name": row.name,
    "group": row.group
  }
  tableLoading.value = true
  resume(data).then(resp => {
    if (resp.success) {
      showNotification("定时任务", "重启定时任务成功")
    } else {
      showNotification("定时任务", resp.message, "warning")
    }
  }).finally(() => {
    getJobList()
    tableLoading.value = false
  })
}
// 修改
const doReschedule = (row) => {
  updateJobForm.cronExpression = row.cronExpression
  updateJobForm.name = row.name
  updateJobForm.description = row.description
  updateJobForm.group = row.group

  updateDialogVisible.value = true
}

function onUpdate() {
  updateFormLoading.value = true
  tableLoading.value = true
  reschedule(updateJobForm).then(resp => {
    if (resp.success) {
      showNotification("定时任务", "修改定时任务成功")
    } else {
      showNotification("定时任务", resp.message, "warning")
    }
  }).finally(() => {
    updateFormLoading.value = false
    updateDialogVisible.value = false
    getJobList()
  })
}
// 删除
const doDel = (row) => {
  showModel("确定要删除该定时任务吗？删除后不可恢复哦！","定时任务", "error").then(() => {
    const data = {
      "name": row.name,
      "group": row.group
    }
    tableLoading.value = true
    del(data).then(resp => {
      if (resp.success) {
        showNotification("定时任务", "删除定时任务成功")
      } else {
        showNotification("定时任务", resp.message, "warning")
      }
    }).finally(() => {
      getJobList()
      tableLoading.value = false
    })
  })
}
// 暂停
const doPause = (row) => {
  const data = {
    "name": row.name,
    "group": row.group
  }
  tableLoading.value = true
  pause(data).then(resp => {
    if (resp.success) {
      showNotification("定时任务", "暂停定时任务成功")
    } else {
      showNotification("定时任务", resp.message, "warning")
    }
  }).finally(() => {
    getJobList()
    tableLoading.value = false
  })}


</script>